package leetcode;

public class LeetCode67 {

    public static void main(String[] args) {
        LeetCode67 leetCode67 = new LeetCode67();
        System.out.println(leetCode67.addBinary("1010", "1011"));
    }

    public String addBinary(String a, String b) {
        StringBuilder sb = new StringBuilder();
        int i = 0, aLength = a.length(), bLength = b.length();
        boolean haveNext = false;
        while (i < aLength || i < bLength) {
            int tmp = getNumByIndex(a, aLength, i) + getNumByIndex(b, bLength, i) + (haveNext ? 1 : 0);
            if (tmp >= 2) {
                haveNext = true;
                tmp %= 2;
            } else
                haveNext = false;
            sb.append(tmp);
            i++;
        }
        if (haveNext)
            sb.append(1);
        return sb.reverse().toString();
    }

    private int getNumByIndex(String str, int length, int i) {
        int index = length - 1 - i;
        return index >= 0 ? str.charAt(index) - '0' : 0;
    }

    //------------------------------------------------------------------
    //转换成10进制数 加减后在转换成二进制
    public String addBinary2(String a, String b) {
        return Integer.toBinaryString(Integer.parseInt(a, 2) + Integer.parseInt(b, 2));
    }
}
